/* internal/js/reservation/maintain.js */

/* Common */

var SERVLET_PATH = '/ordrs/internal/maintain-reservation'; 

/* END Common */


/* Create */

function createReservation () {
	createReservationValidate();
}

//done
function createReservationValidate () {
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var numPeople = document.getElementById('numPeople').value;
	var day = document.getElementById('resDateDay').options[document.getElementById('resDateDay').selectedIndex].value;
	var month = document.getElementById('resDateMonth').selectedIndex;
	var year = document.getElementById('resDateYear').options[document.getElementById('resDateYear').selectedIndex].value;
	var hour = document.getElementById('resDateHour').options[document.getElementById('resDateHour').selectedIndex].value;
	var minute = document.getElementById('resDateMinute').options[document.getElementById('resDateMinute').selectedIndex].value;
	var description = document.getElementById('description').value;
	
	var valid = true;

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');
	/*
	if (lastname == '') { //left blank
		valid = false;
		showFieldRequired('lastnameMessage');
	}*/

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}
	else if (!isNumeric(phone)) {
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}
	else
		hideFieldMessage('phoneMessage');
	

	if (numPeople == '') { //left blank
		valid = false;
		showFieldRequired('numPeopleMessage');
	}
	else if (!isNumeric(numPeople)) {
		valid = false;
		showFieldMessage('numPeopleMessage','Must be number');
	}
	else
		hideFieldMessage('numPeopleMessage');
	
	//TODO check the resTime
	
	if (valid)
		createReservationSend(firstname, lastname, phone, numPeople, day, month, year, hour, minute, description);
}

//done
function createReservationSend (firstname, lastname, phone, numPeople, day, month, year, hour, minute, description) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('c') +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&numPeople=' + encodeURI(numPeople) +
	            '&day=' + encodeURI(day) +
	            '&month=' + encodeURI(month) +
	            '&year=' + encodeURI(year) +
	            '&hour=' + encodeURI(hour) +
	            '&minute=' + encodeURI(minute) +
	            '&description=' + encodeURI(description);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				createReservationReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				createReservationReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}

function createReservationReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		listAllReservationSend();
		showDialog('New reservation created.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Create */

/* Report */

function reportReservation () {
	reportReservationValidate();
}

//done
function reportReservationValidate () {
	var searchOpt = document.getElementById('searchOptForm').elements['searchOpt'];
	if (searchOpt[0].checked)
	{
		var firstname = document.getElementById('firstname').value;
		var lastname = document.getElementById('lastname').value;
		var phone = document.getElementById('phone').value;
		var day = '';
		var month = '';
		var year = '';
	}
	else
	{
		firstname = '';
		lastname = '';
		phone = '';
		day = document.getElementById('resDateDay').options[document.getElementById('resDateDay').selectedIndex].value;
		month = document.getElementById('resDateMonth').selectedIndex;
		year = document.getElementById('resDateYear').options[document.getElementById('resDateYear').selectedIndex].value;
	}
	reportReservationSend(firstname, lastname, phone, day, month, year);
}

//done
function reportReservationSend (firstname, lastname, phone, day, month, year) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('r') +
				'&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
		        '&phone=' + encodeURI(phone) + 
		        '&day=' + encodeURI(day) +
		        '&month=' + encodeURI(month) +
		        '&year=' + encodeURI(year);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				reportReservationReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				reportReservationReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function reportReservationReceive (xml) {
	if (xml.getElementsByTagName('reservations').length > 0) {
		var reservations = xml.getElementsByTagName('reservations')[0];
		showResults(buildTable(reservations));
		if (reservations.childNodes.length == 1)
		{
			showResult(reservations.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10101)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END Report*/

/* Report by month */

function reportReservationByDate (day, month, year, type) {
	reportReservationByDateSend(day, month, year, type);
}

//done
function reportReservationByDateSend (day, month, year, type) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('rd') +
				'&day=' + encodeURI(day) +
		        '&month=' + encodeURI(month) +
		        '&year=' + encodeURI(year) +
		        '&type=' + encodeURI(type);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				reportReservationByDateReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				reportReservationByDateReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function reportReservationByDateReceive (xml) {
	if (xml.getElementsByTagName('reservations').length > 0) {
		var reservations = xml.getElementsByTagName('reservations')[0];
		showResults(buildTable(reservations));
		if (reservations.childNodes.length == 1)
		{
			showResult(reservations.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10101)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END Report by month */

/* Update */

function updateReservation () {
	updateReservationValidate();
}

function updateReservationValidate () {
	var id = document.getElementById('reservationID').value;
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var numPeople = document.getElementById('numPeople').value;
	var day = document.getElementById('resDateDay').options[document.getElementById('resDateDay').selectedIndex].value;
	var month = document.getElementById('resDateMonth').selectedIndex;
	var year = document.getElementById('resDateYear').options[document.getElementById('resDateYear').selectedIndex].value;
	var hour = document.getElementById('resDateHour').options[document.getElementById('resDateHour').selectedIndex].value;
	var minute = document.getElementById('resDateMinute').options[document.getElementById('resDateMinute').selectedIndex].value;
	var description = document.getElementById('description').value;
	
	var valid = true;

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}
	else if (!isNumeric(phone)) {
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}
	else
		hideFieldMessage('phoneMessage');
	

	if (numPeople == '') { //left blank
		valid = false;
		showFieldRequired('numPeopleMessage');
	}
	else if (!isNumeric(numPeople)) {
		valid = false;
		showFieldMessage('numPeopleMessage','Must be number');
	}
	else
		hideFieldMessage('numPeopleMessage');
	
	
	
	//TODO ckeck if the resDate is in the future
	if (valid)
		updateReservationSend(id, firstname, lastname, phone, numPeople, day, month, year, hour, minute, description);
}

//really done
function updateReservationSend (id, firstname, lastname, phone, numPeople, day, month, year, hour, minute, description) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('u') +
	            '&id=' + encodeURI(id) +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&numPeople=' + encodeURI(numPeople) +
	            '&day=' + encodeURI(day) +
	            '&month=' + encodeURI(month) +
	            '&year=' + encodeURI(year) +
	            '&hour=' + encodeURI(hour) +
	            '&minute=' + encodeURI(minute) +
	            '&description=' + encodeURI(description);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				updateReservationReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				updateReservationReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}


function updateReservationReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		listAllReservationSend();
		showDialog('Reservation updated.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Update */


/* Delete */

function deleteReservation () {
	openConfirmModalDialog('Please Confirm',
			'Are you sure you want delete this reservation?','deleteReservationValidate');
}

function deleteReservationValidate () {
	var id = document.getElementById('reservationID').value;
	if (id == '') {
		//no item selected
		showDialog('No Reservation is selected for deletion.');
	} else {
		//item selected
		deleteReservationSend(id);
	}
}


function deleteReservationSend (id) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('d') +
	            '&id=' + encodeURI(id);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				deleteReservationReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				deleteReservationReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function deleteReservationReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		resetFields();
		listAllReservationSend();
		showDialog('Reservation deleted.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Delete */


/* List All */

function listAllReservation () {
	listAllReservationSend();
}

function listAllReservationSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('l');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listAllReservationReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listAllReservationReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listAllReservationReceive (xml) {
	if (xml.getElementsByTagName('reservations').length > 0) {
		var reservations = xml.getElementsByTagName('reservations')[0];
		showResults(buildTable(reservations));
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10201)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List All */


/* List Operation Hour */

function listOperationHour() {
	listOperationHourSend();
}

function listOperationHourSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('o');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listOperationHourReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listOperationHourReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function listOperationHourReceive (xml) {
	if (xml.getElementsByTagName('types').length > 0) {
		var time = new Array(xml.getElementsByTagName('types').length);
		var types = xml.getElementsByTagName('types')[0];
		for (var loop = 0; loop < types.childNodes.length; loop++) {
			var type = types.childNodes[loop];
			var name = type.getElementsByTagName('name')[0].childNodes[0].nodeValue;
			time[loop] = name;
			
			/*var optgroup = document.getElementById('OperationHourOptGroup');
			var opt = document.createElement('option');
			opt.setAttribute('value', name);
			opt.innerHTML = name;
			optgroup.appendChild(opt);*/
		}
		// get start/end time
		for (loop = 0; loop < time.length; loop += 2) {
			var start = time[loop].split(':');
			if (start.length == 2) {
				var startHour = start[0];
				var startMin = start[1];
			}
			else {
				startHour = start[0];
				startMin = 0;
			}
			
			var end = time[loop+1].split(':');
			if (end.length == 2) {
				var endHour = end[0];
				var endMin = end[1];
			}
			else {
				endHour = end[0];
				endMin = 0;
			}
			// register start/end time to optionGroup of reservation Time
			while (startHour < endHour) {
				var optgroup = document.getElementById('resHourOptGroup');
				var opt = document.createElement('option');
				opt.setAttribute('value', startHour);
				opt.innerHTML = startHour++;
				optgroup.appendChild(opt);
			}
			// TODO set the min
		}
		
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10301)
			showDialog(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}


/* END List Operation Hour */


/* Format check */

function isNumeric(strToCheck) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;

	if (strToCheck.length == 0) 
		return false;

	//  test strString consists of valid characters listed above
	for (var i = 0; i < strToCheck.length && blnResult; i++) {
	strChar = strToCheck.charAt(i);
   	if (strValidChars.indexOf(strChar) == -1)
	   blnResult = false;
	}
	return blnResult;
}

/* END Format check */